from HTMLParser import HTMLParser
import httplib
from parse import *
import time                  
from datetime import datetime
#from gmail import GMail,GMailWorker,GMailHandler
from message import Message
import smtplib
from htmlentitydefs import name2codepoint
from telegram import * 
import logging
import random

logging.basicConfig(filename='/home/netsga/ppomppu.log',level=logging.INFO)
latestItemNum = 0
tag_stack = []
attrs_stack = []
msg_old = 'aa'
def send_telegram(msg, link):
    global msg_old
    if msg_old != msg:
        telegram_init()
        telegram_read()
        telegram_send(msg + '-> link: ' + link)
	telegram_close()
    msg_old = msg

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        global tag_stack
        global attrs_stack
        tag_stack.append(tag)
        attrs_stack.append(attrs)
    def handle_endtag(self, tag):
        global tag_stack
        global attrs_stack
        tag_stack.pop()
        attrs_stack.pop()
    def handle_data(self, data):
        global tag_stack
        global attrs_stack
        res = data.lower().find("mazo")
        if res != -1:
            for idx, tag in enumerate(tag_stack):
                if tag == 'a':
                    break
            for attr in attrs_stack[idx]:
                result = search('bbs_view.php?id=ppomppu4&no={:d}',attr[1])
	#	print(attr[1])
                if result != None:
                    global latestItemNum
                    if latestItemNum < result[0]:
                        latestItemNum = result[0]
                        # notification
                        send_telegram(data, 'http://m.ppomppu.co.kr/new/bbs_view.php?id=ppomppu4&no=' + str(latestItemNum))
                        # print data
			logging.info('http://m.ppomppu.co.kr/new/bbs_view.php?id=ppomppu4&no='+str(latestItemNum))
                        logging.info(data)                       


print "Start Parser"
while(1):
    # print "scan"
    logging.info('.')
    parser = MyHTMLParser()

    httpHandle = httplib.HTTPConnection('m.ppomppu.co.kr')
    httpHandle.request("GET", "/new/bbs_list.php?id=ppomppu4")
    r1 = httpHandle.getresponse()
    data1 = r1.read()

    #print data1
    #print "######"

    # clear stacks
    global tag_stack
    del tag_stack[:]
    tag_stack[:] = []
    global attrs_stack
    del attrs_stack[:]
    attrs_stack[:] = []

    parser.feed(unicode(data1,'euc-kr').encode('utf-8'))
    time.sleep(random.randint(2,10))
